/**
 * BatteryLogAction.java
 * Created at 2017-11-13
 * Created by zhanghailin
 * Copyright (C) 2017 BROADTEXT SOFTWARE, All rights reserved.
 */
package com.broadtext.rms.system.action;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Workbook;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.params.ExcelExportEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.broadtext.common.bean.EntityPageBean;
import com.broadtext.common.exp.DaoException;
import com.broadtext.common.exp.ServiceException;
import com.broadtext.common.utils.RmsUtil;
import com.broadtext.common.utils.StringUtils;
import com.broadtext.rms.basic.service.ITmCustomService;
import com.broadtext.rms.system.service.IBatteryLogService;
import com.broadtext.rms.system.service.ISysUserService;
import com.github.miemiedev.mybatis.paginator.domain.PageBounds;

/**
 * <p>ClassName: BatteryLogAction</p>
 * <p>Description: TODO</p>
 * <p>Author: zhanghailin</p>
 * <p>Date: 2017-11-13</p>
 */
@Controller
@RequestMapping("/main/batteryLog")
public class BatteryLogAction {
    
    
    @Autowired
    @Qualifier("batteryLogService")
    private IBatteryLogService batteryLogService;
    
    /**
     * o 注入客户service
     */
    @Autowired
    @Qualifier("tmCustomService")
    private ITmCustomService tmCustomService;
    
    /**
     * 用户Service
     */
    @Autowired
    @Qualifier("sysUserService")
    private ISysUserService sysUserService;
    
    
    /**
     * 
     * <p>Description: TODO</p>
     * @param request
     * @param response
     * @return
     * @throws ServiceException
     */
    @RequestMapping(value = "/findCusNameOpt.mvc")
    @ResponseBody
    public Map<String, Object> findCusNameOpt() {
        Map<String, Object> map = new HashMap<String, Object>();
        map = new HashMap<String, Object>();
        try {
            map.put("data", this.batteryLogService.findCusNameOpt());
        } catch (ServiceException e) {
            e.printStackTrace();
        }
        return map;
    }
    
    /**
     * 
     * <p>Description: TODO</p>
     * @param request
     * @param response
     * @return
     * @throws ServiceException
     */
    @RequestMapping(value = "/getRuntimeLog.mvc")
    @ResponseBody
    public Map<String,Object> getRuntimeLog(HttpServletRequest request, HttpServletResponse response) throws ServiceException {
        PageBounds pageBounds = new PageBounds();
        //解析请求参数，将String字符串转为map
        Map<String,Object> map = new HashMap<String,Object>();
        String aoData = request.getParameter("aoData");
        JSONArray array = JSONArray.parseArray(aoData);
        if (array!=null) {
            Iterator<Object> it = array.iterator();
            while (it.hasNext()) {
                JSONObject obj;
                obj = (JSONObject) it.next();
                if (obj.get("value") != null && StringUtils.isNotBlank(obj.get("value")+"")) {
                    map.put(obj.get("name") + "", obj.get("value"));
                }
            }
        }
        //判断登录账户类型，如果为客户账户则过滤数据，客户类型只看本级和本下级
        Map<String, Object> checkMap;
        List<String> list;
        try {
            checkMap = this.sysUserService.checkUserClass(request.getSession().getAttribute("sys.user").toString());
            if(null != checkMap && "true".equals(checkMap.get("flag").toString())){
                //该用户是客户账号
                map.put("cusId", checkMap.get("cusId"));
                //查询当前登录用户所有下属子节点pk_id
                list = this.tmCustomService.getChildCusIdArray(checkMap.get("cusId")+"");
                map.put("ids", list);
            }
        } catch (DaoException e1) {
            e1.printStackTrace();
        }
        //分页查询条数
        pageBounds.setLimit(Integer.parseInt(map.get("iDisplayLength").toString()));
        //分页第几页
        pageBounds.setPage(Integer.parseInt(map.get("iDisplayStart").toString()) / pageBounds.getLimit() + 1);
        Map<String, Object> dataMap = new HashMap<String, Object>();
        try {

            EntityPageBean<Object> pageBean = this.batteryLogService.getRuntimeLog(map,pageBounds);
            dataMap.put("recordsTotal", pageBean.getiTotalRecords());
            dataMap.put("recordsFiltered", pageBean.getiTotalRecords());
            dataMap.put("aaData", pageBean.getResults());
        } catch (ServiceException e) {
            e.printStackTrace();
        }
        return dataMap;
    }
    
    /**
     * 
     * <p>Description: TODO</p>
     * @param request
     * @param response
     * @return
     * @throws ServiceException
     */
    @RequestMapping(value = "/getBatteryChargeLog2.mvc")
    @ResponseBody
    public Map<String,Object> getBatteryChargeLog2(HttpServletRequest request, HttpServletResponse response) throws ServiceException {
        PageBounds pageBounds = new PageBounds();
        //解析请求参数，将String字符串转为map
        Map<String,Object> map = new HashMap<String,Object>();
        String aoData = request.getParameter("aoData");
        JSONArray array = JSONArray.parseArray(aoData);
        if (array!=null) {
            Iterator<Object> it = array.iterator();
            while (it.hasNext()) {
                JSONObject obj;
                obj = (JSONObject) it.next();
                if (obj.get("value") != null && StringUtils.isNotBlank(obj.get("value")+"")) {
                    map.put(obj.get("name") + "", obj.get("value"));
                }
            }
        }
        //判断登录账户类型，如果为客户账户则过滤数据，客户类型只看本级和本下级
        Map<String, Object> checkMap;
        List<String> list = new ArrayList<String>();
        try {
            checkMap = this.sysUserService.checkUserClass(request.getSession().getAttribute("sys.user").toString());
            if(null != checkMap && "true".equals(checkMap.get("flag").toString())){
                //该用户是客户账号
                map.put("cusId", checkMap.get("cusId"));
                //查询当前登录用户所有下属子节点pk_id
                list = this.tmCustomService.getChildCusIdArray(checkMap.get("cusId")+"");
                map.put("ids", list);
            }
        } catch (DaoException e1) {
            e1.printStackTrace();
        }
        //分页查询条数
        pageBounds.setLimit(Integer.parseInt(map.get("iDisplayLength").toString()));
        //分页第几页
        pageBounds.setPage(Integer.parseInt(map.get("iDisplayStart").toString()) / pageBounds.getLimit() + 1);
        Map<String, Object> dataMap = new HashMap<String, Object>();
        try {

            EntityPageBean<Object> pageBean = this.batteryLogService.getBatteryChargeLog2(map,pageBounds);
            dataMap.put("recordsTotal", pageBean.getiTotalRecords());
            dataMap.put("recordsFiltered", pageBean.getiTotalRecords());
            dataMap.put("aaData", pageBean.getResults());
        } catch (ServiceException e) {
            e.printStackTrace();
        }
        return dataMap;
    }
    
    /**
     * 
     * <p>Description: TODO</p>
     * @param request
     * @param response
     * @return
     * @throws ServiceException
     */
    @RequestMapping(value = "/getBatteryChargeLog.mvc")
    @ResponseBody
    public Map<String,Object> getBatteryChargeLog(HttpServletRequest request, HttpServletResponse response) throws ServiceException {
        //解析请求参数，将String字符串转为map
        Map<String,Object> map = new HashMap<String,Object>();
        String aoData = request.getParameter("aoData");
        JSONArray array = JSONArray.parseArray(aoData);
        if (array!=null) {
            Iterator<Object> it = array.iterator();
            while (it.hasNext()) {
                JSONObject obj;
                obj = (JSONObject) it.next();
                if (obj.get("value") != null && StringUtils.isNotBlank(obj.get("value")+"")) {
                    map.put(obj.get("name") + "", obj.get("value"));
                }
            }
        }
        //判断登录账户类型，如果为客户账户则过滤数据，客户类型只看本级和本下级
        Map<String, Object> checkMap;
        List<String> list;
        try {
            checkMap = this.sysUserService.checkUserClass(request.getSession().getAttribute("sys.user").toString());
            if(null != checkMap && "true".equals(checkMap.get("flag").toString())){
                //该用户是客户账号
                map.put("cusId", checkMap.get("cusId"));
                //查询当前登录用户所有下属子节点pk_id
                list = this.tmCustomService.getChildCusIdArray(checkMap.get("cusId")+"");
                StringBuilder customerIds = new StringBuilder();
                for (String string : list) {
                	if(string.equals("test_cus_id")){
                		break ;
                	}
                	
                    customerIds.append("\""+string+"\",");
                }
                //
                map.put("customerIds", customerIds.substring(0, customerIds.length()));
            }
        } catch (DaoException e1) {
            e1.printStackTrace();
        }
        //分页查询条数
        map.put("limit", Integer.parseInt(map.get("iDisplayLength").toString()));
        //分页第几页
        map.put("page", Integer.parseInt(map.get("iDisplayStart").toString()) / Integer.parseInt(map.get("iDisplayLength").toString()) );
        Map<String, Object> dataMap = new HashMap<String, Object>();
        try {
            List<Object> dataList = this.batteryLogService.getBatteryChargeLog(map);
            long count = this.batteryLogService.getRecordsTotal(map);
            dataMap.put("recordsTotal", count);
            dataMap.put("recordsFiltered", count);
            dataMap.put("aaData", dataList);
        } catch (ServiceException e) {
            e.printStackTrace();
        }
        return dataMap;
    }
    
    /**
     * 
     * <p>Description: 导出电池日志</p>
     * @param response 响应
     * @param request 响应
     * @throws IOException 异常
     * @throws DaoException 异常
     */
    @RequestMapping(value = "/export.mvc")
    public void exportExcel(HttpServletRequest request, HttpServletResponse response) throws IOException, ServiceException{
      //解析请求参数，将String字符串转为map
        Map<String,Object> map = new HashMap<String,Object>();
        String aoData = request.getParameter("aoData");
        JSONArray array = JSONArray.parseArray(aoData);
        if (array!=null) {
            Iterator<Object> it = array.iterator();
            while (it.hasNext()) {
                JSONObject obj;
                obj = (JSONObject) it.next();
                if (obj.get("value") != null && StringUtils.isNotBlank(obj.get("value")+"")) {
                    map.put(obj.get("name") + "", obj.get("value"));
                }
            }
        }
        //判断登录账户类型，如果为客户账户则过滤数据，客户类型只看本级和本下级
        Map<String, Object> checkMap;
        List<String> idlist;
        try {
            checkMap = this.sysUserService.checkUserClass(request.getSession().getAttribute("sys.user").toString());
            if(null != checkMap && "true".equals(checkMap.get("flag").toString())){
                //该用户是客户账号
                map.put("cusId", checkMap.get("cusId"));
                //查询当前登录用户所有下属子节点pk_id
                idlist = this.tmCustomService.getChildCusIdArray(checkMap.get("cusId")+"");
                map.put("ids", idlist);
            }
        } catch (DaoException e1) {
            e1.printStackTrace();
        }
        /*
         * 构建动态map,进行excel导出  
         */
        SimpleDateFormat f = new SimpleDateFormat("yyyyMMddHHmmss");
        String fileName = "电池运行日志"+f.format(new Date());
        String title = "电池运行日志";
        List<ExcelExportEntity> entity = new ArrayList<ExcelExportEntity>();
        //构造方法 列head   列对应字段名      列宽
        entity.add(new ExcelExportEntity("电池ID", "packCode", 20));
        entity.add(new ExcelExportEntity("采集终端ID", "colClientId", 20));
        entity.add(new ExcelExportEntity("所属客户", "cusName", 20));
        entity.add(new ExcelExportEntity("上电时间", "startRuntimeStr", 30));
        entity.add(new ExcelExportEntity("下电时间", "endRuntimeStr", 25));
        entity.add(new ExcelExportEntity("运行时长", "totalRuntimeStr", 15));
        
        /*
         * 封装查询条件进map
         */
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        list = this.batteryLogService.findExportDataList(map);
        
        //调用导出方法进行excel导出
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(
                title, title), entity, list);
        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        workbook.write(bao);
        RmsUtil.exportExcel(fileName.concat(".xls"), response, bao);
        bao.close();
    }
    
    /**
     * 
     * <p>Description: 导出电池日志</p>
     * @param response 响应
     * @param request 响应
     * @throws IOException 异常
     * @throws DaoException 异常
     */
    @RequestMapping(value = "/exportBatteryChargeLog.mvc")
    public void exportBatteryChargeLog(HttpServletRequest request, HttpServletResponse response) throws IOException, ServiceException{
      //解析请求参数，将String字符串转为map
        Map<String,Object> map = new HashMap<String,Object>();
        String aoData = request.getParameter("aoData");
        JSONArray array = JSONArray.parseArray(aoData);
        if (array!=null) {
            Iterator<Object> it = array.iterator();
            while (it.hasNext()) {
                JSONObject obj;
                obj = (JSONObject) it.next();
                if (obj.get("value") != null && StringUtils.isNotBlank(obj.get("value")+"")) {
                    map.put(obj.get("name") + "", obj.get("value"));
                }
            }
        }
        //判断登录账户类型，如果为客户账户则过滤数据，客户类型只看本级和本下级
        Map<String, Object> checkMap;
        List<String> idlist;
        try {
            checkMap = this.sysUserService.checkUserClass(request.getSession().getAttribute("sys.user").toString());
            if(null != checkMap && "true".equals(checkMap.get("flag").toString())){
                //该用户是客户账号
                map.put("cusId", checkMap.get("cusId"));
                //查询当前登录用户所有下属子节点pk_id
                idlist = this.tmCustomService.getChildCusIdArray(checkMap.get("cusId")+"");
                map.put("ids", idlist);
            }
        } catch (DaoException e1) {
            e1.printStackTrace();
        }
        /*
         * 构建动态map,进行excel导出  
         */
        SimpleDateFormat f = new SimpleDateFormat("yyyyMMddHHmmss");
        String fileName = "充电日志"+f.format(new Date());
        String title = "充电日志";
        List<ExcelExportEntity> entity = new ArrayList<ExcelExportEntity>();
        //构造方法 列head   列对应字段名      列宽
        entity.add(new ExcelExportEntity("电池ID", "packCode", 20));
        entity.add(new ExcelExportEntity("采集终端ID", "colClientId", 20));
        entity.add(new ExcelExportEntity("所属客户", "cusName", 30));
        entity.add(new ExcelExportEntity("开始时间", "startTime", 30));
        entity.add(new ExcelExportEntity("结束时间", "endTime", 25));
        entity.add(new ExcelExportEntity("充电时长", "totalChargeTimeStr", 30));
        entity.add(new ExcelExportEntity("充电前SOC", "socStartStr", 15));
        entity.add(new ExcelExportEntity("充电后SOC", "socEndStr", 15));
        
        /*
         * 封装查询条件进map
         */
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        list = this.batteryLogService.findChargeLogDataList(map);
        
        //调用导出方法进行excel导出
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(
                title, title), entity, list);
        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        workbook.write(bao);
        RmsUtil.exportExcel(fileName.concat(".xls"), response, bao);
        bao.close();
    }
    
    
}
